package husc.se.ndung.soiphubaimobile;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;


import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;

import husc.se.ndung.soiphubaimobile.Entity.CongDoan;
import husc.se.ndung.soiphubaimobile.Entity.MaySanXuat;

public class FragmentMaySanXuat extends Fragment implements AbsListView.OnItemClickListener {

    private static final String ARG_CONGDOAN = "MACONGDOAN";

    private String mMaCongDoan;
    private AdapterMaySanXuat adapterMaySanXuat;
    private ArrayList<MaySanXuat> arrayMaySanXuat;
    private ListView mListViewMaySanXuat;
    private ProgressDialog m_ProgressDialog;
    private OnFragmentInteractionMaySanXuatListener mListener;

    // TODO: Rename and change types of parameters
    public static FragmentMaySanXuat newInstance(String maCongDoan) {
        FragmentMaySanXuat fragment = new FragmentMaySanXuat();
        Bundle args = new Bundle();
        args.putString(ARG_CONGDOAN, maCongDoan);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public FragmentMaySanXuat() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mMaCongDoan = getArguments().getString(ARG_CONGDOAN);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item_maysanxuat, container, false);
        mListViewMaySanXuat = (ListView) view.findViewById(R.id.lvMaySanXuat);
        arrayMaySanXuat = new ArrayList<MaySanXuat>();
        adapterMaySanXuat = new AdapterMaySanXuat(getActivity(), R.layout.maysanxuatitem, arrayMaySanXuat);
        //mListViewMaySanXuat = (ListView) view.findViewById(R.id.lvCongDoan);
        mListViewMaySanXuat.setAdapter(adapterMaySanXuat);
        m_ProgressDialog = new ProgressDialog(getActivity());
        m_ProgressDialog.setTitle(getResources().getText(R.string.processing));
        m_ProgressDialog.setMessage(getResources().getText(R.string.waitingLabel));
        // m_ProgressDialog.setProgressStyle(m_ProgressDialog.STYLE_HORIZONTAL);
        m_ProgressDialog.setMax(20);
        m_ProgressDialog.setProgress(0);
        mListViewMaySanXuat.setOnItemClickListener(this);
        aysnGetList();
        return view;
    }

    public void aysnGetList() {

        final AsyncTask<Void, Integer, Void> asyncTaskLoad = new AsyncTask<Void, Integer, Void>() {

            String MsgError;

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    getListMay();
                } catch (Exception e) {
                    Log.d("Loi", e.toString());
                    MsgError = getString(R.string.notFoundData);
                    // Toast.makeText(params[0], , Toast.LENGTH_LONG).show();
                } finally {
                    return null;
                }
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                m_ProgressDialog.show();
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                adapterMaySanXuat.notifyDataSetChanged();
                m_ProgressDialog.dismiss();
                if (MsgError != null && MsgError.length() > 0) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle(getString(R.string.errorTitle));
                    builder.setMessage(MsgError);
                    builder.show();
                }
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
                Log.d("Asyntask values: ", values.toString());
            }
        }.execute();
    }
    public void getListMay() throws Exception {
        ArrayList<String> params = new ArrayList<String>();
        params.add("userName:" + Utils.getValueByKey(getActivity(), "UserName", ""));
        params.add("passWord:" + Utils.getValueByKey(getActivity(), "Password", ""));
        params.add("maCongDoan:" + mMaCongDoan);
        SoapObject soapArray = (SoapObject) Utils.sendRequest(getActivity(), "GetListMaySanXuat", params);
        arrayMaySanXuat.clear();
        Log.d("So phan tu", soapArray.getPropertyCount() + "");
        for (int i = 0; i < soapArray.getPropertyCount(); i++) {
            SoapObject soapItem = (SoapObject) soapArray.getProperty(i);
            String id = soapItem.getProperty("MaMaySanXuat").toString();
            String tenMaySanXuat = soapItem.getProperty("TenMaySanXuat").toString();
            String canhBao = soapItem.getProperty("CanhBao").toString();
            arrayMaySanXuat.add(new MaySanXuat(id,
                    tenMaySanXuat, canhBao));
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionMaySanXuatListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (null != mListener) {
            // Notify the active callbacks interface (the activity, if the
            // fragment is attached to one) that an item has been selected.
            mListener.onFragmentInteractionMaySanXuat(arrayMaySanXuat.get(position));
        }
    }

    /**
     * The default content for this Fragment has a TextView that is shown when
     * the list is empty. If you would like to change the text, call this method
     * to supply the text it should use.
     */
    public void setEmptyText(CharSequence emptyText) {
        View emptyView = mListViewMaySanXuat.getEmptyView();

        if (emptyView instanceof TextView) {
            ((TextView) emptyView).setText(emptyText);
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionMaySanXuatListener {
        // TODO: Update argument type and name
        public void onFragmentInteractionMaySanXuat(MaySanXuat may);
    }

}
